package LibDL.recommender.data.utils;

import LibDL.core.Dtype;
import LibDL.core.TensorOptions;
import LibDL.core.functional;
import LibDL.data.LibArrayInt;
import com.google.common.annotations.Beta;
import com.google.common.collect.ArrayTable;
import com.google.common.collect.Table;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import net.librec.math.structure.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NumUtils {

//    static <T extends Number> void add(List<T> self, T value) {
//    }

    public static void listAdd(List<Integer> self, int value) {
        for (int i = 0; i < self.size(); i++) {
            self.set(i, self.get(i) + value);
        }
    }

    public static void listAdd1(List<Integer> self, int value) throws InterruptedException {
        //long start = System.currentTimeMillis();
        int length = self.size();
        int threadNum = 8;
        int threadSize = length/threadNum;
        ExecutorService pool = Executors.newFixedThreadPool(8);
        int begin;
        int end;
        for(int i=0;i<threadNum;i++){
            if(i == threadNum - 1){
                begin=threadSize * i;
                end=length;
            } else {
                begin=threadSize * i;
                end=threadSize * (i + 1);
            }
            MyThread task = new MyThread(self,begin,end,value);
            pool.execute(task);
        }
        pool.shutdown();
        while(true){
            if(pool.isTerminated()) {
                //System.out.println("执行任务listAdd消耗了 ：" + (System.currentTimeMillis() - start) + "毫秒");
                break;
            }
        }
    }

    static class MyThread extends Thread{
        private List<Integer> self;
        private int begin;
        private  int end;
        private int value;
        public MyThread(List<Integer> self, int begin, int end, int value) {
            this.self = self;
            this.begin=begin;
            this.end=end;
            this.value=value;
        }
        public void run() {
            //System.out.println("["+begin+","+end+"]...");
            for(int i=begin;i<end;i++){
                self.set(i,self.get(i)+value);
            }
            //System.out.println("["+begin+","+end+"]finish");
        }
    }

    public static <T extends Comparable<T>> ArrayList<Integer> argsort(List<T> self) {
        ArrayList<Integer> sorted = new ArrayList<Integer>(self.size());
        for (int i=0;i<self.size();i++) {
            sorted.add(i,i);
        }
        sorted.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return self.get(o1).compareTo(self.get(o2));
            }
        });
        return sorted;
    }

    public static <T extends Comparable<T>> ArrayList<Integer> argsort(List<T> self, Comparator<Integer> comparator) {
        ArrayList<Integer> sorted = new ArrayList<Integer>(self.size());
        for (int i=0;i<self.size();i++) {
            sorted.add(i,i);
        }
        sorted.sort(comparator);
        return sorted;
    }

    public static <T extends Comparable<T>> ArrayList<Integer> argsort(int[] self) { //TODO REMOVE
        ArrayList<Integer> sorted = new ArrayList<Integer>(self.length);
        for (int i=0;i<self.length;i++) {
            sorted.add(i,i);
        }
        sorted.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return self[o1] - (self[o2]);
            }
        });
        return sorted;
    }

    public static void sort(ArrayList<Long> self) {
        self.sort(Comparator.naturalOrder());
    }

    public static <T> ArrayList<T> index_select(List<T> self, List<Integer> indices) { // TODO REMOVE
        ArrayList<T> out = new ArrayList<>(indices.size());
        for (int i = 0; i < indices.size(); i++) {
            out.add(i, self.get(indices.get(i)));
        }
        return out;
    }
    public static int[] index_select(int[] self, List<Integer> indices) {
        int[] out = new int[indices.size()];
        for (int i = 0; i < indices.size(); i++) {
            out[i] = self[indices.get(i)];
        }
        return out;
    }

    public static ArrayList<Integer>[] unique(List<Integer> self, boolean return_index, boolean return_inverse,boolean return_counts) {
        ArrayList<Integer> unique, unique_indeces, unique_inverse, unique_counts;
        ArrayList<Integer> sorted =NumUtils.<Integer>argsort(self);
        int tmp = 0;
        unique = new ArrayList<>(self.size());
        unique.add(0,self.get(sorted.get(0)));
        unique_indeces = new ArrayList<>(self.size());
        if(return_index) {
            unique_indeces.add(0, sorted.get(0));
        }
        unique_inverse = new ArrayList<>(self.size());
        if(return_inverse) {
            for (int i = 0; i < self.size(); i++) {
                unique_inverse.add(i, -1);
            }
            unique_inverse.set(sorted.get(0), 0);
        }
        unique_counts = new ArrayList<>(self.size());
        if(return_counts) {
            unique_counts.add(0, 1);
        }
        tmp++;
        while(tmp<sorted.size()) {
            if(self.get(sorted.get(tmp)).equals(unique.get(unique.size()-1))){
                if(return_counts) {
                    unique_counts.set(unique.size() - 1, unique_counts.get(unique.size() - 1) + 1);
                }
                if(return_inverse) {
                    unique_inverse.set(sorted.get(tmp), unique.size() - 1);
                }
                if(return_index) {
                    if (sorted.get(tmp) < unique_indeces.get(unique.size() - 1)) {
                        unique_indeces.set(unique.size() - 1, sorted.get(tmp));
                    }
                }
            }else{
                unique.add(unique.size(),self.get(sorted.get(tmp)));
                if(return_counts) {
                    unique_counts.add(unique.size() - 1, 1);
                }
                if(return_inverse) {
                    unique_inverse.set(sorted.get(tmp), unique.size() - 1);
                }
                if(return_index) {
                    unique_indeces.add(unique.size() - 1, sorted.get(tmp));
                }
            }
            tmp++;
        }
        unique.trimToSize();
        unique_indeces.trimToSize();
        unique_inverse.trimToSize();
        unique_counts.trimToSize();
        if(return_index){
            if(return_inverse){
                if(return_counts){
                    return new ArrayList[]{unique,unique_indeces,unique_inverse,unique_counts};
                }
                return new ArrayList[]{unique,unique_indeces,unique_inverse};
            }
            if(return_counts){
                return new ArrayList[]{unique,unique_indeces,unique_counts};
            }
            return new ArrayList[]{unique,unique_indeces};
        }
        if(return_inverse){
            if(return_counts){
                return new ArrayList[]{unique,unique_inverse,unique_counts};
            }
            return new ArrayList[]{unique,unique_inverse};
        }
        if(return_counts){
            return new ArrayList[]{unique,unique_counts};
        }
        return new ArrayList[]{unique};
    }
    public static ArrayList<Integer>[] unique(int[] self, boolean return_index, boolean return_inverse,boolean return_counts) {
        ArrayList<Integer> unique, unique_indeces, unique_inverse, unique_counts;
        ArrayList<Integer> sorted =NumUtils.<Integer>argsort(self);
        int tmp = 0;
        unique = new ArrayList<>(self.length);
        unique.add(0,self[sorted.get(0)]);
        unique_indeces = new ArrayList<>(self.length);
        if(return_index) {
            unique_indeces.add(0, sorted.get(0));
        }
        unique_inverse = new ArrayList<>(self.length);
        if(return_inverse) {
            for (int i = 0; i < self.length; i++) {
                unique_inverse.add(i, -1);
            }
            unique_inverse.set(sorted.get(0), 0);
        }
        unique_counts = new ArrayList<>(self.length);
        if(return_counts) {
            unique_counts.add(0, 1);
        }
        tmp++;
        while(tmp<sorted.size()) {
            if(self[sorted.get(tmp)] == (unique.get(unique.size()-1))){
                if(return_counts) {
                    unique_counts.set(unique.size() - 1, unique_counts.get(unique.size() - 1) + 1);
                }
                if(return_inverse) {
                    unique_inverse.set(sorted.get(tmp), unique.size() - 1);
                }
                if(return_index) {
                    if (sorted.get(tmp) < unique_indeces.get(unique.size() - 1)) {
                        unique_indeces.set(unique.size() - 1, sorted.get(tmp));
                    }
                }
            }else{
                unique.add(unique.size(),self[sorted.get(tmp)]);
                if(return_counts) {
                    unique_counts.add(unique.size() - 1, 1);
                }
                if(return_inverse) {
                    unique_inverse.set(sorted.get(tmp), unique.size() - 1);
                }
                if(return_index) {
                    unique_indeces.add(unique.size() - 1, sorted.get(tmp));
                }
            }
            tmp++;
        }
        unique.trimToSize();
        unique_indeces.trimToSize();
        unique_inverse.trimToSize();
        unique_counts.trimToSize();
        if(return_index){
            if(return_inverse){
                if(return_counts){
                    return new ArrayList[]{unique,unique_indeces,unique_inverse,unique_counts};
                }
                return new ArrayList[]{unique,unique_indeces,unique_inverse};
            }
            if(return_counts){
                return new ArrayList[]{unique,unique_indeces,unique_counts};
            }
            return new ArrayList[]{unique,unique_indeces};
        }
        if(return_inverse){
            if(return_counts){
                return new ArrayList[]{unique,unique_inverse,unique_counts};
            }
            return new ArrayList[]{unique,unique_inverse};
        }
        if(return_counts){
            return new ArrayList[]{unique,unique_counts};
        }
        return new ArrayList[]{unique};
    }

    public static <T extends Number> void setItem(DenseVector vector, List<T> value, int offset) {
        for (int i = 0; i < value.size(); i++) {
            vector.set(i + offset, value.get(i).doubleValue());
        }
    }

    public static <T extends Number> void setItem(DenseVector vector, LibArrayInt value, int offset) {
        for (int i = 0; i < value.size(); i++) {
            vector.set(i + offset, (double) value.elementData[i]);
        }
    }

    public static boolean any(DenseMatrix matrix) {
        for (int i = 0; i < matrix.rowSize(); i++) {
            for (int j = 0; j < matrix.columnSize(); j++) {
                if (matrix.get(i, j) != 0)
                    return true;
            }
        }
        return false;
    }

    public static DenseMatrix row_shuffle(DenseMatrix matrix, List<Integer> indices) {
        int n = matrix.rowSize();
        if (indices == null)
            indices = new ArrayList<Integer>(functional.randperm(n, new TensorOptions((Dtype.INT64))).tolist_long());
        DenseMatrix out = new DenseMatrix(matrix.rowSize(), matrix.columnSize());
        for (int i = 0; i < n; i++) {
            out.set(i, matrix.row(indices.get(i)));
        }
        return out;
    }

    public static List<Integer> arange(int start, int end, int step) {
        int n = (end - start) / step;
        ArrayList<Integer> out = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            out.add(i, (start + step * i));
        }
        return out;
    }

    public static void elementWise_(List<Float> self, FloatCalculator calculator) {
        for (int i = 0; i < self.size(); i++) {
            self.set(i, calculator.calculate(self.get(i)));
        }
    }
    public static void elementWise_(List<Integer> self, IntCalculator calculator) {
        for (int i = 0; i < self.size(); i++) {
            self.set(i, calculator.calculate(self.get(i)));
        }
    }

    /**
     * @return data type is LONG */
    @Beta
    static SequentialAccessSparseMatrix create(
            List<Integer> row_indices, List<Integer> col_indices, List<? extends Number> values,
            Integer row, Integer col) {
        assert row_indices.size() == col_indices.size();
        Table<Integer, Integer, Long> table = NumUtils.create(row_indices, col_indices);
        for (int i = 0; i < row_indices.size(); i++) {
            table.put(row_indices.get(i), col_indices.get(i), values.get(i).longValue());
        }
        return new SequentialAccessSparseMatrix(row, col, table);
    }
    @Beta
    static SequentialAccessSparseMatrix create(
            List<Integer> row_indices, List<Integer> col_indices, long default_value,
            Integer row, Integer col) {
        assert row_indices.size() == col_indices.size();
        Table<Integer, Integer, Long> table = NumUtils.create(row_indices, col_indices);
        for (int i = 0; i < row_indices.size(); i++) {
            table.put(row_indices.get(i), col_indices.get(i), default_value);
        }
        return new SequentialAccessSparseMatrix(row, col, table);
    }
    @SuppressWarnings("UnstableApiUsage")
    private static Table<Integer, Integer, Long> create(List<Integer> row_indices, List<Integer> col_indices) {
        List<Integer> row = NumUtils.unique(row_indices, false, false,false)[0];
        List<Integer> col = NumUtils.unique(col_indices, false, false,false)[0];
        return ArrayTable.create(row, col);
    }

//    @Beta
//    public static RowSequentialAccessSparseMatrix createRSASparseMatrix(
//            int[] row_indices, List<Integer> col_indices, long value,
//            Integer rows, Integer cols) {
//        RowSequentialAccessSparseMatrix matrix;
//        List<Integer>[] out = NumUtils.unique(row_indices, false, false,true);
//        List<Integer> row_unique = out[0];
//        List<Integer> counts = out[1];
//        int n = row_unique.size();
//        VectorBasedSequentialSparseVector[] rowVectors = new VectorBasedSequentialSparseVector[n];
//        int index = 0;
//        for (int i = 0; i < n; i++) {
//            List<Integer> col = col_indices.subList(index, index + counts.get(i));
//            index += counts.get(i);
//            rowVectors[i] = new VectorBasedSequentialSparseVector(
//                    cols, new IntArrayList(col), NumUtils.createArr(col.size(), (double) value));
//        }
//        matrix = new RowSequentialAccessSparseMatrix(rows, cols, rowVectors);
//        return matrix;
//    }
    @Beta
    public static RowSequentialAccessSparseMatrix createRSASparseMatrix(
            LibArrayInt row_indices, LibArrayInt col_indices, long value,
            Integer rows, Integer cols) {
        RowSequentialAccessSparseMatrix matrix;
        LibArrayInt[] out = row_indices.unique(false, false,true);
        LibArrayInt row_unique = out[0];
        LibArrayInt counts = out[1];
        int n = row_unique.size();
        VectorBasedSequentialSparseVector[] rowVectors = new VectorBasedSequentialSparseVector[n];
        int index = 0;
        for (int i = 0; i < n; i++) {
            LibArrayInt col = col_indices.subList(index, index + counts.get(i));
            index += counts.get(i);
            rowVectors[i] = new VectorBasedSequentialSparseVector(
                    cols, new IntArrayList(col.elementData), NumUtils.createArr(col.size(), (double) value)); // TODO CHECKBOUNDS
        }
        matrix = new RowSequentialAccessSparseMatrix(rows, cols, rowVectors);
        return matrix;
    }
    private static DoubleArrayList createArr(int length, double value) {
        double[] out = new double[length];
        for (int i = 0; i < length; i++) {
            out[i] = value;
        }
        return new DoubleArrayList(out);
    }

    public static double sum(List<? extends Number> input) {
        double sum = 0.0;
        for (Number item :
                input) {
            sum += item.doubleValue();
        }
        return sum;
    }

    public static double mean(List<? extends Number> input) {
        return NumUtils.sum(input) / input.size();
    }
}


